// 导入behavior 封装
import wxValidate from 'wechat-validate'
const app = getApp()
Page({
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
    redirectURL: ''
  },
  // 要注入一下
  behaviors: [wxValidate],
  // 插件提供的
  rules: {
    mobile: [{
        required: true,
        message: '请填写手机号码!'
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请填写正确的手机号码!'
      }
    ],
    code: [{
        required: true,
        message: '请填写验证码!'
      },
      {
        pattern: /^\d{6}$/,
        message: '请填写正确的验证码!'
      }
    ]
  },
  onLoad({
    redirectURL
  }) {
    this.setData({
      redirectURL
    })
  },
  async getSMSCode() {
    // 验证mobile
    // valid  是否校验通过 布尔值
    // message 如果校验没通过  返回那条规则的message
    const {
      valid,
      message
    } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    this.setData({
      countDownVisible: true
    })
    // 掉接口获取验证码
    const {
      code,
      data
    } = await wx.http.get('/code', {
      mobile: this.data.mobile
    })
    if (code !== 10000) return wx.utils.toast()
    console.log(data.code)
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 点击登录
  async submitForm() {
    // 验证码 rules 中定义的全部数据
    const isAllValid = this.validate()
    if (!isAllValid) return
    // 调用登录接口 不要和axios弄混了
    const {
      code,
      data
    } = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code
    })
    if (code !== 10000) return wx.utils.toast('登录失败')
    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)
    const whiteList = ['/pages/index/index', '/pages/my/index']
    if (this.data.redirectURL) {
      if (whiteList.includes(this.data.redirectURL)) {
        // 回到刚才拦截到登录的页面(refreshtoken失效)
        wx.switchTab({
          url: this.data.redirectURL,
        })
      } else {
        // 回到刚才拦截到登录的页面(token失效)
        wx.redirectTo({
          url: this.data.redirectURL,
        })
      }
    } else {
      // 没遇到拦截,正常登录去首页
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  }
})